<template>
  <el-dialog
    :title="title"
    v-model="open"
    width="500px"
    append-to-body
    :close-on-press-escape="false"
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="排序字段" prop="sortValue">
        <el-input-number
          style="width: 300px"
          v-model="form.sortValue"
          placeholder="请输入排序字段"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
  import { computed, ref, watch } from 'vue';
  import modal from '@/plugins/modal';
  import {
    addSdkLmKbIndustry,
    updateSdkLmKbIndustry,
  } from '@/api/intelligencebase/sdkLmKbIndustry';

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },

    title: {
      type: String,
      default: 'add',
    },
    data: {
      type: Object,
      default: () => ({}),
    },
  });
  const emit = defineEmits(['update:modelValue', 'refresh']);

  const rules = ref([
    { name: [{ required: true, message: '请填写行业名称' }] },
    // { catId: [{ required: true, message: '请选择所属分类' }] },
  ]);
  const formRef = ref(null);
  const form = ref({
    id: null,
    name: null,
    sortValue: null,
  });

  const open = computed({
    get() {
      return props.modelValue;
    },
    set(val) {
      emit('update:modelValue', val);
    },
  });

  watch(
    () => props.modelValue,
    (val) => {
      if (!val) return;
      init();
    },
  );

  function init() {
    reset();

    if (props.data) {
      form.value = {
        ...props.data,
      };
    }
  }

  function reset() {
    form.value = {
      id: null,
      name: null,
      sortValue: null,
      createBy: null,
      createTime: null,
      updateBy: null,
      updateTime: null,
    };
    formRef.value?.resetFields();
  }
  function cancel() {
    open.value = false;
  }
  function submitForm() {
    formRef.value.validate((valid) => {
      if (valid) {
        if (form.value.id) {
          updateSdkLmKbIndustry(form.value).then(() => {
            modal.msgSuccess('修改成功');
            open.value = false;
            emit('refresh');
          });
        } else {
          addSdkLmKbIndustry(form.value).then(() => {
            modal.msgSuccess('新增成功');
            open.value = false;
            emit('refresh');
          });
        }
      }
    });
  }
</script>
<style lang="scss" scoped></style>
